<template>
    <div class="product-list">
        <search-bar v-model="searchName" left-arrow show-action action-text="搜索"
                    @click-left="handleRouteBack"
                    @search="handleSearch"
                    @action="handleSearch"/>
        <product-filtering-bar @change="handleChangeFiltering"/>
        <product-list :name="name" :sort="sort"/>
    </div>
</template>

<script>
  import SearchBar from "@/components/SearchBar"
  import WhiteSpace from "@/components/WhiteSpace"
  import ProductList from "@/components/product/ProductList"
  import ProductFilteringBar from "@/components/product/ProductFilteringBar"
  import _ from "lodash"

  export default {
    name: "ProductListView",
    components: {
      ProductFilteringBar,
      SearchBar,
      WhiteSpace,
      ProductList,
    },
    props: {
      name: {
        type: String,
        default: "",
      },
    },
    data() {
      return {
        sort: undefined,
        searchName: "",
      }
    },
    created() {
      this.searchName = this.name
    },
    methods: {
      handleRouteBack() {
        this.$router.back()
      },
      handleSearch(name) {
        console.log(name)
        this.$router.replace({
          path: "/products",
          query: { name },
        })
      },
      handleChangeFiltering(filtering) {
        console.log(filtering)
        const { sort } = filtering
        if (sort) {
          const sorts = []
          if (_.has(sort, "price")) {
            sorts.push(`price:${_.get(sort, "price")}`)
          }
          if (_.has(sort, "totalSales")) {
            sorts.push(`total_sales:${_.get(sort, "totalSales")}`)
          }
          this.sort = _.join(sorts, ",")
        } else {
          this.sort = undefined
        }
      },
    },
  }
</script>

<style lang="scss" scoped>
    .product-list {

    }
</style>
